//
//  SettingViewController.m
//  Growth
//
//  Created by 洪波 陈 on 5/30/12.
//  Copyright (c) 2012 MEETStudio. All rights reserved.
//

#import "SettingViewController.h"


#import "ModifyViewController.h"

#import "CJSONSerializer.h"
#import "WebRequest.h"

#import "ServiceContentViewController.h"
#import "PrivacyPolicyViewController.h"
#import "ContactUsViewController.h"
#import "HelpViewController.h"
#import "PersonalViewController.h"
#import "PersonalLetterViewController.h"
#import "WebRequest.h"
#import "UserSettingViewController.h"
#import "NotificationEngine.h"

#import "SinaShareMethod.h"

#import "HospitalIntroductionViewController.h"

static WebConnectionArray *settingList_connection;
static WebConnectionArray *settingModify_connection;

@interface SettingViewController ()

@end

@implementation SettingViewController

@synthesize myScrollView;


@synthesize onlyWifiSwitch;
@synthesize wifi3GSwitch;
@synthesize photoQualitySwitch;
@synthesize recordAlertSwitch;
@synthesize recordAlertTimeLabel;
@synthesize lanbaoshuoAlertSwitch;
@synthesize lanbaoshuoAlertTimeLabel;
@synthesize eventAlertSwitch;
@synthesize vaccineAlertSwitch;
@synthesize trendAlertSwitch;

//时间选择
@synthesize timeView;
@synthesize timePickerView;

@synthesize webSettingDict;

@synthesize passwordTextField;

- (void)dealloc
{
    [myScrollView release];
    
    [onlyWifiSwitch release];
    [wifi3GSwitch release];
    [photoQualitySwitch release];
    [recordAlertSwitch release];
    [recordAlertTimeLabel release];
    [lanbaoshuoAlertSwitch release];
    [lanbaoshuoAlertTimeLabel release];
    [eventAlertSwitch release];
    [vaccineAlertSwitch release];
    [trendAlertSwitch release];
    [versionTips release];
    
    
    [webSettingDict release];
    

    [timeView release];
    [timePickerView release];

    
    if (passwordTextField != nil) {
        [passwordTextField release];
    }
    
    
    if (settingList_connection != nil) {
        settingList_connection.connectionDelegate = nil;
        [settingList_connection release];
        settingList_connection = nil;
    }
    
    if (settingModify_connection != nil) {
        settingModify_connection.connectionDelegate = nil;
        [settingModify_connection release];
        settingModify_connection = nil;
    }
    
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.tabBarItem.image = [UIImage imageNamed:@"icon_more.png"];
        self.tabBarItem.title = @"设置";
        self.title = @"设置";
        
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [myScrollView setContentSize:CGSizeMake(320, 600)];
    
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    
    [self setTItleWith:@"设置"];
    
    [onlyWifiSwitch setOn:!ALBUM_UPLOAD_IS_3G animated:NO];
    [wifi3GSwitch  setOn:ALBUM_UPLOAD_IS_3G animated:NO];
    [photoQualitySwitch  setOn:PHOTO_IS_HD animated:NO];
    [recordAlertSwitch  setOn:RECORD_ALERT animated:NO];
    recordAlertTimeLabel.text = RECORD_ALERT_TIME;
    [lanbaoshuoAlertSwitch  setOn:LANBAOSHUO_ALERT animated:NO];
    lanbaoshuoAlertTimeLabel.text = LANBAOSHUO_ALERT_TIME;
    [eventAlertSwitch  setOn:EVENT_ALERT animated:NO];
    [vaccineAlertSwitch  setOn:VACCINE_ALERT animated:NO];
    [trendAlertSwitch  setOn:TREND_ALERT animated:NO];
    
    
    self.myScrollView.scrollEnabled = YES;
    [[NotificationEngine sharedNotificationEngine] postDeviceToken];
    
    webSettingDict = nil;
    [self loadWebSettingData];
    
    //如果有新版本给出提示
    NSString *version = [[NSUserDefaults standardUserDefaults] valueForKey:GROWTH_LASTEST_VERSION_KEY];
    
    if (version != nil) {
        NSString *currentVersion;
        NSDictionary *info = [[NSBundle mainBundle] infoDictionary];
        currentVersion = [info objectForKey:(NSString *)kCFBundleVersionKey];
        
        float currentVersionFloat = [currentVersion floatValue];
        float lastestVersionFloat = [version floatValue];
        
        CLog(@"New version %f  Locale version %f", lastestVersionFloat, currentVersionFloat);
        
        if (currentVersionFloat < lastestVersionFloat) {
            versionTips.hidden = NO;
        }
        else{
            versionTips.hidden = YES;
        }
    }
    else{
        versionTips.hidden = YES;
    }
    
    [myScrollView setContentSize:CGSizeMake(320, 700)];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
    self.myScrollView = nil;
    self.wifi3GSwitch = nil;
    self.photoQualitySwitch = nil;
    self.recordAlertSwitch = nil;
    self.recordAlertTimeLabel = nil;
    self.eventAlertSwitch = nil;
    self.vaccineAlertSwitch = nil;
    self.trendAlertSwitch = nil;
    
    self.timeView = nil;
    self.timePickerView = nil;
    self.passwordTextField = nil;
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - LoadSetting Data
- (void)loadWebSettingData
{
    int uid = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];
    NSMutableURLRequest *request = [WebRequest settingsRequtestWith:uid];
    
    CLog(@"setting request %@", request);
    if (settingList_connection != nil) {
        settingList_connection.connectionDelegate = nil;
    }
    settingList_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
}

#pragma mark -Connection Delegate
- (void)connectionArraySuccess:(NSDictionary *)dict connectionURL:(NSString *)url
{
    NSRange range = [url rangeOfString:@"alert/setting/modify"];
    if (range.length >0) {
        
        NSString *result = [dict objectForKey:@"object"];
        if (![result isMemberOfClass:[NSNull class]]) {
            if ([result boolValue]) {
                [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"保存成功"];
                isChange = NO;
                [self.navigationItem setRightBarButtonItem:nil];
                CLog(@"modify result %@", dict);
            }
            else {
                [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"保存失败"];
            }
        }
        
        return;
    }
    
    range = [url rangeOfString:@"password/modify"];
    if(range.length > 0){
        CLog(@"password modify result %@", dict);
        NSDictionary *objectDict = [dict objectForKey:@"object"];
        NSNumber *errorCode = [objectDict objectForKey:@"errorCode"];
        if (![errorCode isMemberOfClass:[NSNull class]] && [errorCode intValue] == 0) {
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"密码设置成功，可以安全退出了！"];
            
            [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:REGIST_LOGIN_KEY];
            
        }
        else {
            [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"密码设置出错，请重试" duration:DEFAULT_LOADING_TIME];
        }
     
        return;
    }
    
    range = [url rangeOfString:@"alert/setting?uid"];
    if (range.length >0) {
        CLog(@"setting dict %@", dict);
        
        NSDictionary *settingDict = [dict objectForKey:@"object"];
        webSettingDict = [[NSDictionary alloc] initWithDictionary:settingDict];
        [self settingWithWebData];
        CLog(@"setting dict %@", webSettingDict);
        
        return;
    }
}

- (void)connectionArrayError:(NSError *)error
{
    CLog(@"setting error %@", error);
}


#pragma mark - Setting Change
- (void)showEditButton 
{
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(settingModifyAction:)];
    [self.navigationItem setRightBarButtonItem:rightButtonItem];
}

- (void)settingModifyAction:(id)sender
{
    //    Object userIdObject = maps.get("uid");
    //    Object diaryAlertObject = maps.get("diaryAlert"); //  日志提醒
    //    Object diaryAlertTimeObject = maps.get("diaryAlertTime");//  日志提醒时间 整数0~23
    //    Object lanbaoAlertObject = maps.get("lanbaoAlert");//  蓝宝说提醒
    //    Object lanbaoAlertTimeObject = maps.get("lanbaoAlertTime");//  蓝宝说提醒时间 整数0~23
    //    Object eventAlertObject = maps.get("eventAlert");//  大事件提醒
    //    Object vaccineAlertObject = maps.get("vaccineAlert");//  疫苗提醒
    //    Object trendAlertObject = maps.get("trendAlert");//  动态提醒
    NSArray *valueArray = [self settingValueArray];
    //NSArray *keyArray = [NSArray arrayWithObjects:@"uid", @"diaryAlert", @"diaryAlertTime", @"lanbaoAlert", @"lanbaoAlertTime", @"eventAlert", @"vaccineAlert", @"trendAlert",  nil];
    NSArray *keyArray = [NSArray arrayWithObjects:@"uid", @"eventAlert", @"vaccineAlert", @"trendAlert",  nil];

    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    
    NSData *jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [WebRequest settingModifyRequestWith:jsonData] ;
    
    CLog(@"request %@", request);
    if (settingModify_connection != nil) {
        settingModify_connection.connectionDelegate = nil;
    }
    settingModify_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
}

- (NSArray *)settingValueArray
{

    NSString *uid;
    NSString *diaryAlert;
    NSString *diaryAlertTime;
    NSString *lanbaoAlert;
    NSString *lanbaoAlertTime;
    NSString *eventAlert;
    NSString *vaccineAlert;
    NSString *trendAlert;
    
    uid = [[NSUserDefaults standardUserDefaults] valueForKey:@"userId"];
    diaryAlert = [[NSUserDefaults standardUserDefaults] valueForKey:RECORD_ALERT_KEY];
    NSString *diaryTimeStr = recordAlertTimeLabel.text;
    diaryAlertTime = [diaryTimeStr stringByReplacingOccurrencesOfString:@":00" withString:@""];
    
    lanbaoAlert = [[NSUserDefaults standardUserDefaults] valueForKey:LANBAOSHUO_ALERT_KEY];
    NSString *lanbaTimeStr = lanbaoshuoAlertTimeLabel.text;
    lanbaoAlertTime = [lanbaTimeStr stringByReplacingOccurrencesOfString:@":00" withString:@""];
    eventAlert = [[NSUserDefaults standardUserDefaults] valueForKey:EVENT_ALERT_KEY];
    vaccineAlert = [[NSUserDefaults standardUserDefaults] valueForKey:VACCINE_ALERT_KEY];
    trendAlert = [[NSUserDefaults standardUserDefaults] valueForKey:TREND_ALERT_KEY];
    
    //NSArray *array = [NSArray arrayWithObjects:uid, diaryAlert, diaryAlertTime, lanbaoAlert,lanbaoAlertTime, eventAlert, vaccineAlert, trendAlert, nil];
    NSArray *array = [NSArray arrayWithObjects:uid, eventAlert, vaccineAlert, trendAlert, nil];

    return array;

}


- (void)settingWithWebData
{
    if (webSettingDict != nil && webSettingDict) {
        
        webSyn = YES;
//        NSString *diaryAlert = [webSettingDict objectForKey:@"diaryAlert"];
//        NSString *diaryAlertTime = [webSettingDict objectForKey:@"diaryAlertTime"];
//        NSString *lanbaoAlert = [webSettingDict objectForKey:@"lanbaoAlert"];
//        NSString *lanbaoAlertTime = [webSettingDict objectForKey:@"lanbaoAlertTime"];
        NSString *eventAlert = [webSettingDict objectForKey:@"eventAlert"];
        NSString *vaccineAlert = [webSettingDict objectForKey:@"vaccineAlert"];
        NSString *trendAlert = [webSettingDict objectForKey:@"trendAlert"];
        
        //日志
//        if (![diaryAlert isMemberOfClass:[NSNull class]]) {
//            [recordAlertSwitch setOn:[diaryAlert boolValue]];
//            [self recordAlertAction:recordAlertSwitch];
//        }

        
        //日志时间
//        if (![diaryAlertTime isMemberOfClass:[NSNull class]]) {
//            recordAlertTimeLabel.text = [NSString stringWithFormat:@"%02d:00", [diaryAlertTime intValue]]; 
//        }
        
        //懒宝说
//        if (![lanbaoAlert isMemberOfClass:[NSNull class]]) {
//            [lanbaoshuoAlertSwitch setOn:[lanbaoAlert boolValue]];
//            [self lanbaoshuoAlertAction:lanbaoshuoAlertSwitch];
//        }
        
        //懒宝说时间
//        if (![lanbaoAlertTime isMemberOfClass:[NSNull class]]) {
//            lanbaoshuoAlertTimeLabel.text = [NSString stringWithFormat:@"%02d:00", [lanbaoAlertTime intValue]];
//        }

        
        //大事件
        if (![eventAlert isMemberOfClass:[NSNull class]]) {
            [eventAlertSwitch setOn:[eventAlert boolValue]];
            [self eventAlertAction:eventAlertSwitch];
        }
        
        //疫苗
        if (![vaccineAlert isMemberOfClass:[NSNull class]]) {
            [vaccineAlertSwitch setOn:[vaccineAlert boolValue]];
            [self vaccineAlertAction:vaccineAlertSwitch];
        }
        
        //动态
        if (![trendAlert isMemberOfClass:[NSNull class]]) {
            [trendAlertSwitch setOn:[trendAlert boolValue]];
            [self trendAlertAction:trendAlertSwitch];
        }
        
        
        webSyn = NO;
        
    }
}

#pragma mark - action

//仅wifi
- (IBAction)onlyWifiAction:(id)sender
{
    UISwitch *switchButton = (UISwitch *)sender;
    if (switchButton.on) {
        [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:ALBUM_UPLOAD_IS_3G_KEY];
        [wifi3GSwitch setOn:NO];
    }
    else {
        [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:ALBUM_UPLOAD_IS_3G_KEY];
         [wifi3GSwitch setOn:YES];
    }
    
}

//wifi和3g
- (IBAction)wifi3GAction:(id)sender
{
    UISwitch *switchButton = (UISwitch *)sender;
    if (switchButton.on) {
        [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:ALBUM_UPLOAD_IS_3G_KEY];
        [onlyWifiSwitch setOn:NO];
    }
    else {
        [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:ALBUM_UPLOAD_IS_3G_KEY];
        [onlyWifiSwitch setOn:YES];
    }
    
}

//高清图片
- (IBAction)photoQualityAction:(id)sender
{
    UISwitch *switchButton = (UISwitch *)sender;
    if (switchButton.on) {
        [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:PHOTO_IS_HD_KEY];
    }
    else {
        [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:PHOTO_IS_HD_KEY];
    }
    
}



//记录提醒
- (IBAction)recordAlertAction:(id)sender
{
//    if (!webSyn) {
//        if (!isChange) {
//            isChange = YES;
//            [self showEditButton];
//        }
//    }

    UISwitch *switchButton = (UISwitch *)sender;
    if (switchButton.on) {
        [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:RECORD_ALERT_KEY];
    }
    else {
        [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:RECORD_ALERT_KEY];
    }
    
}

//懒宝说提醒
- (IBAction)lanbaoshuoAlertAction:(id)sender
{
//    if (!webSyn) {
//        if (!isChange) {
//            isChange = YES;
//            [self showEditButton];
//        }
//    }
    
    UISwitch *switchButton = (UISwitch *)sender;
    if (switchButton.on) {
        [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:LANBAOSHUO_ALERT_KEY];
    }
    else {
        [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:LANBAOSHUO_ALERT_KEY];
    }
    
}

//大事记提醒
- (IBAction)eventAlertAction:(id)sender
{
    if (!webSyn) {
        if (!isChange) {
            isChange = YES;
            [self showEditButton];
        }
    }
    
    UISwitch *switchButton = (UISwitch *)sender;
    if (switchButton.on) {
        [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:EVENT_ALERT_KEY];
    }
    else {
        [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:EVENT_ALERT_KEY];
    }
    
}

//疫苗提醒
- (IBAction)vaccineAlertAction:(id)sender
{
    if (!webSyn) {
        if (!isChange) {
            isChange = YES;
            [self showEditButton];
        }
    }
    
    UISwitch *switchButton = (UISwitch *)sender;
    if (switchButton.on) {
        [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:VACCINE_ALERT_KEY];
    }
    else {
        [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:VACCINE_ALERT_KEY];
    }
    
}

//动态提醒
- (IBAction)trendAlertAction:(id)sender
{
    if (!webSyn) {
        if (!isChange) {
            isChange = YES;
            [self showEditButton];
        }
    }
    
    UISwitch *switchButton = (UISwitch *)sender;
    if (switchButton.on) {
        [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:TREND_ALERT_KEY];
    }
    else {
        [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:TREND_ALERT_KEY];
    }
    
}



- (void)notificationCheck
{
    NSString *deviceToken = [[NSUserDefaults standardUserDefaults] valueForKey:DEVICE_TOKEN_KEY];
    
    if (deviceToken == nil || [deviceToken isEqualToString:@""]) {
        
    }

}

#pragma mark -

//私信
- (IBAction)personalLetter:(id)sender{
    
    PersonalLetterViewController *viewController = [[PersonalLetterViewController alloc] init];
	[self.navigationController pushViewController:viewController animated:YES];
    [viewController release];
     
}

//个人资料修改
- (IBAction)personnalModify:(id)sender{
    
    UserSettingViewController * viewController = [[UserSettingViewController alloc]init];
    
    viewController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:viewController animated:YES ];
    [viewController release];
    
}


//我的喜欢
- (IBAction)myFavorAction:(id)sender{
    
 }

#pragma mark -

//版本更新
- (IBAction)versionUpdate:(id)sender{
    
    
    VersionUpdateClass *versionUpdateClass  = [VersionUpdateClass shareVersionUpdateClass];
    
    [versionUpdateClass checkVersion ];
    
    
}


- (IBAction)helpAction:(id)sender
{
    HelpViewController *content = [[HelpViewController alloc] init];
    [self.navigationController pushViewController:content animated:YES];
    [content release];
}

//服务条款
- (IBAction)serviceContentAction:(id)sender
{
    ServiceContentViewController *content = [[ServiceContentViewController alloc] init];
    [self.navigationController pushViewController:content animated:YES];
    [content release];
}

//隐私政策
- (IBAction)privacyPolicyAction:(id)sender
{
    PrivacyPolicyViewController *content = [[PrivacyPolicyViewController alloc] init];
    [self.navigationController pushViewController:content animated:YES];
    [content release];
}

//联系我们
- (IBAction)contactUsAction:(id)sender
{
    HospitalIntroductionViewController *content = [[HospitalIntroductionViewController alloc] init];
    content.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:content animated:YES];
    [content release];
}

- (IBAction)feedbackAction:(id)sender
{
    [self feedbackEmailWith:nil];
}

//评星
- (IBAction)gradeAction:(id)sender
{
    NSString *str = [NSString stringWithFormat:@"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%d",525681769 ];  
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
}

// 推荐APP
- (IBAction)recmooendAction:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"您要使用邮件还是短信邀请？"delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"短信发送", @"邮件发送", nil];
    
    actionSheet.tag = 110;
    [actionSheet showInView:self.view];
    
    [actionSheet release];
    
}


//清空缓存
- (IBAction)cleanCacheAction:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"确定清空图片缓存？"delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"确定" otherButtonTitles:nil];
    actionSheet.tag = 120;
    [actionSheet showInView:self.view];
    [actionSheet release];

}

#pragma mark 修改密码
- (IBAction)modifyKey:(id)sender{
    
    
    ModifyViewController *viewCont =  [[ModifyViewController alloc]init];
    viewCont.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:viewCont animated:YES];
    [viewCont release];
    
}


- (void)cleanCache
{
    [[SDDataCache sharedDataCache:kImageCache_Default] clearDisk];
    [[SDDataCache sharedDataCache:kImageCache_Content_Icon] clearDisk];
    [[SDDataCache sharedDataCache:kImageCache_Content_Browse] clearDisk];
    [[SDDataCache sharedDataCache:kImageCache_Album_Icon] clearDisk];
    [[SDDataCache sharedDataCache:kImageCache_Album_Browse] clearDisk];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (actionSheet.tag) {
        case 110:
        {
            switch (buttonIndex) {
                case 0:
                {
                    [self sendSMSWith:nil];
                    break;
                }
                case 1:
                {
                    [self sendEmailWith:nil];
                }
                default:
                    break;
            }
            break;
        }
        case 120:
        {
            CLog(@"缓存 %d",buttonIndex);
            switch (buttonIndex) {
                case 0:
                {
                    [self cleanCache];
                    break;
                }
                case 1:
                {
                    break;
                }
                default:
                    break;
            }
            break;
        }
        default:
            break;
    }

}


#pragma mark - feedback email

- (void)feedbackEmailWith:(NSString *)email
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    
	if (mailClass != nil) {
        //[self displayMailComposerSheet];
		// We must always check whether the current device is configured for sending emails
        
        if ([mailClass canSendMail]) {
			[self displayFeedbackMailComposerSheetWith:@"support@lanbaoo.com"];
		}
		else {
			[self launchMailAppOnDeviceWith:email];
		}
	}
	else	{
		[LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"您的设备不能发邮件哦！" duration:DEFAULT_LOADING_TIME];
	}
}

// Displays an email composition interface inside the application. Populates all the Mail fields. 
-(void)displayFeedbackMailComposerSheetWith:(NSString *)emailStr 
{
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	
	[picker setSubject:@"印象宝贝意见反馈"];

	// Fill out the email body text
    
    NSArray *toRecipients = [NSArray arrayWithObject:emailStr]; 
	
	[picker setToRecipients:toRecipients];

    double sysVersion = [[[UIDevice currentDevice] systemVersion] doubleValue];
    NSString *userNickName = [[NSUserDefaults standardUserDefaults] valueForKey:@"userName"];
    NSString *platform = [self platformString];
    NSString *bodyStr = [NSString stringWithFormat:@"\n\n\n\n\n昵称:%@\nDevice Version:%@\nAPP Version:%@\niOS Version:%f", userNickName,platform ,VERSION, sysVersion ];
    
	[picker setMessageBody:bodyStr isHTML:NO];
	
	[self presentModalViewController:picker animated:YES];
	[picker release];
}

// Launches the Mail application on the device.
-(void)launchFeedbackMailAppOnDeviceWith:(NSString *)emailStr
{
    double sysVersion = [[[UIDevice currentDevice] systemVersion] doubleValue];
    
    NSString *userNickName = [[NSUserDefaults standardUserDefaults] valueForKey:@"userName"];
       
    NSString *platform = [self platformString];
    NSString *bodyStr = [NSString stringWithFormat:@"\n\n\n\n\n昵称:%@\nDevice Version:%@\nAPP Version:%@\niOS Version:%f", userNickName,platform ,VERSION, sysVersion ];
    
	NSString *recipients = [NSString stringWithFormat:@"mailto:%@?subject=印象宝贝意见反馈", emailStr] ;
	NSString *body = [NSString stringWithFormat:@"&body=%@", bodyStr] ;
    
	
	NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
	email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}



#pragma mark - 时间选择器

- (IBAction)showAlertTimePickerAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    NSInteger index = button.tag;
    [self.view addSubview:timeView];

    timePickerView.tag = index;
}

- (IBAction)timePickerDoneAction:(id)sender
{
    int index = timePickerView.tag;
    NSInteger row = [timePickerView selectedRowInComponent:0];
    switch (index) {
        case 0:     //记录时间
        {
            NSString *timeStr = [NSString stringWithFormat:@"%02d:00", row];
            [[NSUserDefaults standardUserDefaults] setValue:timeStr forKey:RECORD_ALERT_TIME_KEY];
            recordAlertTimeLabel.text = timeStr;
//            if (!webSyn) {
//                if (!isChange) {
//                    isChange = YES;
//                    [self showEditButton];
//                }
//            }
            break;
        }
        case 1:     //懒宝说时间
        {
            NSString *timeStr = [NSString stringWithFormat:@"%02d:00", row];
            [[NSUserDefaults standardUserDefaults] setValue:timeStr forKey:LANBAOSHUO_ALERT_TIME_KEY];
            lanbaoshuoAlertTimeLabel.text = timeStr;
//            if (!webSyn) {
//                if (!isChange) {
//                    isChange = YES;
//                    [self showEditButton];
//                }
//            }
            break;
        }
        default:
            break;
    }
    
    [timeView removeFromSuperview];
}

- (IBAction)timePickerCancleAction:(id)sender
{
    [timeView removeFromSuperview];
}

#pragma mark Picker View

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [NSString stringWithFormat:@"%02d:00", row];
}



#pragma mark Picker View DataSource
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return 24;
}
#pragma mark -
#pragma mark 退出登陆 begin

- (IBAction)logoutAction:(id)sender{
    
    if ([[[NSUserDefaults standardUserDefaults] valueForKey:REGIST_LOGIN_KEY] boolValue]) {
        //设置密码
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"您的账户还没有密码，请先设置密码再退出！\n\n"
                                                       delegate:self 
                                              cancelButtonTitle:nil otherButtonTitles:nil];
        
        [alert addButtonWithTitle:@"取消"];
        [alert addButtonWithTitle:@"确定"];

        [alert setCancelButtonIndex:0];
        
        if (passwordTextField == nil) {
            passwordTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 60.0, 260.0, 26.0)];
            passwordTextField.delegate = self;
            [passwordTextField setBackgroundColor:[UIColor whiteColor]];
            [passwordTextField setBorderStyle:UITextBorderStyleRoundedRect];
            [passwordTextField setPlaceholder:@"请输入密码"];
            [passwordTextField setSecureTextEntry:YES];
            
        }
        
        passwordTextField.text = nil;

        [alert addSubview:passwordTextField];
    
        
        alert.tag = 110;
        
        
        [alert show];
        [alert release];
        
        return;
    }
    else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"是否确定退出？" message:nil
                                                       delegate:self 
                                              cancelButtonTitle:@"否" otherButtonTitles:nil];
        
        [alert addButtonWithTitle:@"是"];
        alert.tag = 120;
        
        [alert show];
        [alert release];
    }
    
}

#pragma mark - Password Setting
- (void)passwordModifyWith:(NSString *)passWord
{
    NSString *userId = [[NSUserDefaults standardUserDefaults] valueForKey:@"userId"];
    
    NSArray *valueArray = [NSArray arrayWithObjects:userId, passWord, nil];

    NSArray *keyArray = [NSArray arrayWithObjects:@"uid", @"password", nil];
    
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    
    NSData *jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [WebRequest passwordModifyRequestWith:jsonData] ;
    
    CLog(@"request %@", request);
    if (settingModify_connection != nil) {
        settingModify_connection.connectionDelegate = nil;
    }
    settingModify_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
}


#pragma mark alert view  delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag == 110) {
        
        if (buttonIndex == 0) {
            return;
        }
        else {
            NSString *password = passwordTextField.text;
            CLog(@"password %@", password);
            
            
            if (password != nil && password.length >0) {
                [self passwordModifyWith:password];
            }
            else {
                [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"密码不能为空！"];
            }
            
        }
       
        
        
    }
    else if(alertView.tag == 120){
        if (buttonIndex == 1) { //退出登陆
            [self logoutHandle];
        }
    }
    
    
}

#pragma mark 退出

- (void)logoutHandle
{
     [self.navigationController popToRootViewControllerAnimated:NO];
    
    [self clearUserInfo];
    
    [self  loadLoginView];
    
   
}

- (void)clearUserInfo {
    
    
    
    //删除图片缓存
    [[SDDataCache sharedDataCache:kImageCache_Default] clearDisk];
    [[SDDataCache sharedDataCache:kImageCache_Content_Icon] clearDisk];
    [[SDDataCache sharedDataCache:kImageCache_Content_Browse] clearDisk];
    [[SDDataCache sharedDataCache:kImageCache_Album_Icon] clearDisk];
    [[SDDataCache sharedDataCache:kImageCache_Album_Browse] clearDisk];
    
    PublicDatabaseEngine *databaseEngine = [PublicDatabaseEngine sharedDatabaseEngine];
    
    //删除缓存的日志
    NSString *sql1 = [NSString stringWithFormat:@"delete from DiaryViews"];
    
    [databaseEngine executeSQL:sql1];
    
    //删除动态缓存
    NSString *sqlNews = [NSString stringWithFormat:@"delete from News"];
    
    [databaseEngine executeSQL:sqlNews];
    
    NSString *sqlPopulars = [NSString stringWithFormat:@"delete from Populars"];
    
    [databaseEngine executeSQL:sqlPopulars];

    //删除家庭缓存
    NSString *sqlfamily = [NSString stringWithFormat:@"delete from family_view"];
    
    [databaseEngine executeSQL:sqlfamily];
    
    
    //删除可管理的时间轴列表信息
    NSString *sql2 = [NSString stringWithFormat:@"delete from TimelineId"];
    [databaseEngine executeSQL:sql2];
    
    
    //删除每个宝宝的时间轴信息
    NSString *sql4 = [NSString stringWithFormat:@"delete from TimelineInfo"];
    [databaseEngine executeSQL:sql4];
    
    //删除安全验证信息
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Ucenter-Code"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Ucenter-VerifyCode"];
    
    //删除个人信息
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userId"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userName"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userAttachmentId"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:QQOpenId];

    
    

    //删除宝宝信息
    if ([[NSUserDefaults standardUserDefaults] valueForKey:BABY_ATTACHMENTID]) {
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:BABY_ATTACHMENTID];
    }
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"timelineId"]) {
        
         [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"timelineId"];
    }
    
    
    if ([[NSUserDefaults standardUserDefaults] valueForKey:BABYINFO]) {
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:BABYINFO]; 
        
    }
    

    SinaShareMethod *sinaShareMethod = [SinaShareMethod sharedSinaShareMethod];
    [sinaShareMethod.weiBoEngine logOut];
}

- (void)loadLoginView{
    
    GrowthAppDelegate *appDelegate = 
    (GrowthAppDelegate *)[[UIApplication sharedApplication] delegate];
    
    LoginViewController *con = [[LoginViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:con];
   
    [appDelegate.firstController presentModalViewController:nav animated:YES];
    [con release];
    [nav release];
    
       
}

#pragma --
#pragma mark end



#pragma mark -
#pragma mark Compose Mail/SMS


- (void)sendSMSWith:(NSString *)phoneNumStr
{
    Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
	
	if (messageClass != nil) { 			
		// Check whether the current device is configured for sending SMS messages
		if ([messageClass canSendText]) {
			[self displaySMSComposerSheetWith:phoneNumStr];
		}
		else {	
			[LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"您的设备不支持发短信哦！" duration:DEFAULT_LOADING_TIME];
            
		}
	}
	else {
		[LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"您的设备不支持发短信哦！" duration:DEFAULT_LOADING_TIME];
	}
}


- (void)sendEmailWith:(NSString *)email
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    
	if (mailClass != nil) {
        //[self displayMailComposerSheet];
		// We must always check whether the current device is configured for sending emails
        
        if ([mailClass canSendMail]) {
			[self displayMailComposerSheetWith:email];
		}
		else {
			[self launchMailAppOnDeviceWith:email];
		}
	}
	else	{
		[LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"您的设备不能发邮件哦！" duration:DEFAULT_LOADING_TIME];
	}
}

// Displays an email composition interface inside the application. Populates all the Mail fields. 
-(void)displayMailComposerSheetWith:(NSString *)emailStr 
{
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	
	[picker setSubject:@"我正在使用印象宝贝"];
	
	
	// Set up recipients
	//NSArray *toRecipients = [NSArray arrayWithObject:emailStr]; 
	
	//[picker setToRecipients:toRecipients];
	
	// Attach an image to the email
    //	NSString *path = [[NSBundle mainBundle] pathForResource:@"rainy" ofType:@"jpg"];
    //	NSData *myData = [NSData dataWithContentsOfFile:path];
    //	[picker addAttachmentData:myData mimeType:@"image/jpeg" fileName:@"rainy"];
	
	// Fill out the email body text
    NSString *userNickName = [[NSUserDefaults standardUserDefaults] valueForKey:@"userName"];
    NSString *bodyStr = [NSString stringWithFormat:@"我正在使用印象宝贝， 如果你通过http://www.lanbaoo.com/app/download 下载，就可以和我一起记录并分享宝宝的精彩瞬间啦。记得加我为好友哦，我的昵称是%@。 【印象宝贝——移动互联时代儿童成长亲密助手】",userNickName ];
	[picker setMessageBody:bodyStr isHTML:NO];
	
	[self presentModalViewController:picker animated:YES];
	[picker release];
}

// Launches the Mail application on the device.
-(void)launchMailAppOnDeviceWith:(NSString *)emailStr
{
    NSString *userNickName = [[NSUserDefaults standardUserDefaults] valueForKey:@"userName"];
    NSString *bodyStr = [NSString stringWithFormat:@"我正在使用印象宝贝， 如果你通过http://www.lanbaoo.com/app/download 下载，就可以和我一起记录并分享宝宝的精彩瞬间啦。记得加我为好友哦，我的昵称是%@。 【印象宝贝——移动互联时代儿童成长亲密助手】",userNickName ];
    
	NSString *recipients = [NSString stringWithFormat:@"mailto:%@?subject=我正在使用印象宝贝", emailStr] ;
	NSString *body = [NSString stringWithFormat:@"&body=%@", bodyStr] ;
    
	
	NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
	email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}

// Displays an SMS composition interface inside the application. 
-(void)displaySMSComposerSheetWith:(NSString *)phoneNumStr 
{
	MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
    
    //NSArray *phoneArray = [NSArray arrayWithObjects:phoneNumStr, nil];
    
    //[picker setRecipients:phoneArray];
    
    NSString *userNickName = [[NSUserDefaults standardUserDefaults] valueForKey:@"userName"];
    NSString *bodyStr = [NSString stringWithFormat:@"我正在使用印象宝贝， 如果你通过http://www.lanbaoo.com/app/download 下载，就可以和我一起记录并分享宝宝的精彩瞬间啦。记得加入我的家庭哦，我的昵称是%@。 【印象宝贝——移动互联时代儿童成长亲密助手】",userNickName ];
    [picker setBody:bodyStr];
    
	picker.messageComposeDelegate = self;
	
	[self presentModalViewController:picker animated:YES];
	[picker release];
}
#pragma mark -
#pragma mark Dismiss Mail/SMS view controller

// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the 
// message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller 
          didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MFMailComposeResultCancelled:
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"邮件已取消"];
			break;
		case MFMailComposeResultSaved:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"邮件已保存"];
			break;
		case MFMailComposeResultSent:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"邮件已发送"];
			break;
		case MFMailComposeResultFailed:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"邮件发送失败"];
			break;
		default:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"邮件发送失败"];
			break;
	}
	[self dismissModalViewControllerAnimated:YES];
}


// Dismisses the message composition interface when users tap Cancel or Send. Proceeds to update the 
// feedback message field with the result of the operation.
- (void)messageComposeViewController:(MFMessageComposeViewController *)controller 
                 didFinishWithResult:(MessageComposeResult)result {
    
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MessageComposeResultCancelled:
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"短信已取消"];
			break;
		case MessageComposeResultSent:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"短信已发送"];
			break;
		case MessageComposeResultFailed:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"短信发送失败"];
			break;
		default:
			[LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"短信发送失败"];
			break;
	}
	[self dismissModalViewControllerAnimated:NO];
}



#pragma mark -Device Version

-(NSString *) platformString{
    
    NSString *platform = [self platform];

    //    iPhone         (iPhone1,1)
    //    iPhone3G       (iPhone1,2)
    //    iPhone3GS      (iPhone2,1)
    //    iPhone4        (iPhone3,1)
    //    iPhone4(vz)    (iPhone3,3)iPhone4 CDMA版
    //    iPhone4S       (iPhone4,1)
    
    //    iPodTouch(1G)  (iPod1,1)
    //    iPodTouch(2G)  (iPod2,1)
    //    iPodTouch(3G)  (iPod3,1)
    //    iPodTouch(4G)  (iPod4,1)
    
    //    iPad           (iPad1,1)
    //    iPad2,1        (iPad2,1)Wifi版
    //    iPad2,2        (iPad2,2)GSM3G版
    //    iPad2,3        (iPad2,3)CDMA3G版
    
    //    AppleTV(2G)    (AppleTV2,1)

    
    if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone 1G(iPhone1,1)";
    if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G(iPhone1,2)";
    if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS(iPhone2,1)";
    if ([platform isEqualToString:@"iPhone3,1"])    return @"iPhone 4(iPhone3,1)";
    if ([platform isEqualToString:@"iPhone3,3"])    return @"iPhone 4(iPhone3,3)";
    if ([platform isEqualToString:@"iPhone4,1"])    return @"iPhone 4S(iPhone4,1)";
    
    if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    
    if ([platform isEqualToString:@"iPad1,1"])      return @"iPad(iPad1,1)";
    if ([platform isEqualToString:@"iPad2,1"])      return @"iPad2(iPad2,1)";
    if ([platform isEqualToString:@"iPad2,2"])      return @"iPad2(iPad2,2)";
    if ([platform isEqualToString:@"iPad2,3"])      return @"iPad2(iPad2,3)";
    
    if ([platform isEqualToString:@"i386"])         return @"Simulator";
    
    
    
    return platform;
    
}

- (NSString *) platform
{  
    size_t size;  
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);  
    char *machine = malloc(size);  
    sysctlbyname("hw.machine", machine, &size, NULL, 0);  
    NSString*platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];  
    free(machine);  
    return platform;  
}

#pragma mark - 默认设置初始化
+ (void)defaultSetting
{
    
    static NSString *is3G = @"0";
    static NSString *photoHDQuality = @"0";
    static NSString *diaryAlert = @"1";
    static NSString *diaryAlertTime = @"20:00";
    static NSString *eventAlert = @"1";
    static NSString *vaccineAlert = @"1";
    static NSString *trendAlert = @"0";
    
    NSString *isDefaultSetting = [[NSUserDefaults standardUserDefaults] objectForKey:DEFAULT_SETTING_KEY];
    
    if (![isDefaultSetting boolValue]) {
        
        CLog(@"Default setting!");
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setValue:is3G forKey:ALBUM_UPLOAD_IS_3G_KEY];
        [userDefaults setValue:photoHDQuality forKey:PHOTO_IS_HD_KEY];
        [userDefaults setValue:diaryAlert forKey:RECORD_ALERT_KEY];
        [userDefaults setValue:diaryAlertTime forKey:RECORD_ALERT_TIME_KEY];
        [userDefaults setValue:eventAlert forKey:EVENT_ALERT_KEY];
        [userDefaults setValue:vaccineAlert forKey:VACCINE_ALERT_KEY];
        [userDefaults setValue:trendAlert forKey:TREND_ALERT_KEY];
        
        [userDefaults setValue:@"1" forKey:DEFAULT_SETTING_KEY];
    }
    
    
}







@end
